package io.openkunlun.javadsl.springboot.server;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;

import java.net.InetAddress;
import java.util.UUID;

@Data
@ConfigurationProperties(prefix = "dapr.server")
public class DaprServerProperties {

    public static final String DEFAULT_HOST = "<getHostAddress>";
    public static final int DEFAULT_PORT = 9000;
    public static final int DEFAULT_TTL = 15;
    public static final int DEFAULT_WEIGHT = 100;
    public static final int DEFAULT_WARMUP = 15_000;

    private String id;
    private String host = DEFAULT_HOST;
    private int port = DEFAULT_PORT;
    private int ttl = DEFAULT_TTL;
    private int weight = DEFAULT_WEIGHT;
    private int warmup = DEFAULT_WARMUP;

    public String getId() {
        if (null == id || id.isEmpty()) {
            id = UUID.randomUUID().toString().replace("-", "");
        }
        return id;
    }

    public String getHost() {
        try {
            if ("<getHostAddress>".equals(host)) {
                return InetAddress.getLocalHost().getHostAddress();
            }

            if ("<getHostName>".equals(host)) {
                return InetAddress.getLocalHost().getHostName();
            }

            return host;
        } catch (Exception e) {
            return host;
        }
    }

    public DaprServerProperties setHost(String host) {
        this.host = host;
        return this;
    }

    public int getTtl() {
        if (ttl <= 0) {
            ttl = DEFAULT_TTL;
        }
        return ttl;
    }

    public int getWeight() {
        if (weight <= 0) {
            weight = DEFAULT_WEIGHT;
        }
        return weight;
    }

    public int getWarmup() {
        if (warmup <= 0) {
            warmup = DEFAULT_WARMUP;
        }
        return warmup;
    }
}
